package com.jinkaimen.goodcash.ui.activity;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.DialogUtils;
import com.ht.baselibs.utils.UIUtils;
import com.jinkaimen.goodcash.R;
import com.jinkaimen.goodcash.bean.PreWithdrawBean;
import com.jinkaimen.goodcash.bean.WithdrawBean;
import com.jinkaimen.goodcash.dao.AccountDao;
import com.jinkaimen.goodcash.manager.ApiManager;
import com.jinkaimen.goodcash.thread.ValidateThread;

import retrofit2.Call;
import retrofit2.Response;

public class WithdrawActivity extends BaseActivity {

    private TextView mValidateBtnView;
    private EditText mMoneyView;
    private PreWithdrawBean mPreWithdrawBean;
    private TextView mLeftMoneyView;
    private TextView mCardNoAndBankNameView;
    private TextView mGetMoneyView;
    private TextView mAvaliableMoneyView;
    private Dialog mWithdrawDialog;
    private TextView mDialogTelView;

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void initTitleBar() {
        mTitleBarView.setTitleText("提现");
    }

    @Override
    protected int initContentView() {
        return R.layout.activity_withdraw;
    }

    @Override
    protected void initChildView() {
        mAvaliableMoneyView = (TextView) findViewById(R.id.tv_activity_withdraw_avaliable_money);

        mMoneyView = (EditText) findViewById(R.id.et_activity_withdraw_money);
        mLeftMoneyView = (TextView) findViewById(R.id.tv_activity_withdraw_left);
        mGetMoneyView = (TextView) findViewById(R.id.tv_activity_withdraw_get);
        mCardNoAndBankNameView = (TextView) findViewById(R.id.tv_activity_withdraw_cardNoAndBankName);

        initSendCodeDialog();
    }

    @Override
    protected void initChildData() {
        ApiManager.getApi().preWithdraw(
                "HSY001032",
                AccountDao.getInstance().getAccount().accountID,
                101
        ).enqueue(new NetCallBack<PreWithdrawBean>() {
            @Override
            protected void onSuccess(Call<PreWithdrawBean> call, Response<PreWithdrawBean> response) {
                mPreWithdrawBean = response.body();
                mLeftMoneyView.setText("手续费："+mPreWithdrawBean.poundage);
                mCardNoAndBankNameView.setText(mPreWithdrawBean.bankName+"（"+mPreWithdrawBean.cardNo+"）");
                mAvaliableMoneyView.setText("￥"+mPreWithdrawBean.available);
            }
        });

    }

    @Override
    protected void setChildViewListener() {
        findViewById(R.id.btn_activity_withdraw).setOnClickListener(this);

        mMoneyView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String withDrawMoneyString = mMoneyView.getText().toString();
                if (!TextUtils.isEmpty(withDrawMoneyString)){
                    double withDrawMoney = Double.parseDouble(withDrawMoneyString);
                    if (withDrawMoney <= mPreWithdrawBean.available){
                        mGetMoneyView.setText("到账金额："+(withDrawMoney-mPreWithdrawBean.poundage));
                    } else {
                        UIUtils.showToast("可用余额不足");
                    }
                }
            }
        });
    }

    public void initSendCodeDialog(){
        View dialogView = View.inflate(this, R.layout.dialog_withdraw, null);
        mWithdrawDialog = DialogUtils.showDialog(this, dialogView);
        dialogView.findViewById(R.id.iv_dialog_withdraw_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWithdrawDialog.hide();
            }
        });

        mValidateBtnView = (TextView) dialogView.findViewById(R.id.btn_dialog_withdraw_get_validate);
        mDialogTelView = (TextView) dialogView.findViewById(R.id.tv_dialog_withdraw_tel);
        final EditText mValidateView = (EditText) dialogView.findViewById(R.id.ev_dialog_withdraw_validate);

        mValidateBtnView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                sendCode();
            }
        });


        dialogView.findViewById(R.id.btn_activity_withdraw).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                withdraw(mValidateView);
            }
        });
    }

    private void sendCode() {
        mValidateBtnView.setEnabled(false);
        showLoadingDialogCanotCancle();
        ApiManager.getApi().withdrawCode(
                "HSY001034",
                AccountDao.getInstance().getAccount().accountID
        ).enqueue(new NetCallBack<String>() {
            @Override
            protected void onSuccess(Call<String> call, Response<String> response) {
                new ValidateThread(mHandler).start();
                mValidateBtnView.setTextColor(Color.parseColor("#bebebe"));
            }

            @Override
            protected void hiddenProgress() {
                hideLodingDialog();
            }
        });
    }

    private void withdraw(EditText mValidateView) {
        showLoadingDialogCanotCancle();
        ApiManager.getApi().withdraw(
            "HSY001031",
            mMoneyView.getText().toString(),
            101,
            AccountDao.getInstance().getAccount().accountID,
            mValidateView.getText().toString()
        ).enqueue(new NetCallBack<WithdrawBean>() {
            @Override
            protected void onSuccess(Call<WithdrawBean> call, Response<WithdrawBean> response) {
                WithdrawBean withdrawBean = response.body();
                UIUtils.showToast(withdrawBean.msg);
                if (withdrawBean.code != 0){
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString(BindSuccessActivity.BANK_NAME, mPreWithdrawBean.bankName+" 尾号"+mPreWithdrawBean.cardNo);
                bundle.putString(BindSuccessActivity.WITHDRAW_MONEY, mMoneyView.getText()+"元");
                bundle.putString(BindSuccessActivity.LEFT_MONEY, mPreWithdrawBean.poundage+"元");

                String withDrawMoneyString = mMoneyView.getText().toString();
                if (!TextUtils.isEmpty(withDrawMoneyString)){
                    double withDrawMoney = Double.parseDouble(withDrawMoneyString);
                    bundle.putString(BindSuccessActivity.GET_MONEY, (withDrawMoney-mPreWithdrawBean.poundage)+"元");
                }
                ActivityUtils.startActivityAndFinish(WithdrawActivity.this, BindSuccessActivity.class, bundle);
            }

            @Override
            protected void hiddenProgress() {
                hideLodingDialog();
            }
        });
    }

    @Override
    protected void handleMessage(BaseActivity context, Message msg) {
        switch (msg.what){
            case 100:
                mValidateBtnView.setText(msg.obj.toString());

                break;
            case 200:
                mValidateBtnView.setTextColor(Color.parseColor("#6284dd"));
                mValidateBtnView.setText("获取验证码");
                mValidateBtnView.setEnabled(true);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.btn_activity_withdraw:
                if (mPreWithdrawBean == null){
                    return;
                }

                String withDrawMoneyString = mMoneyView.getText().toString();
                if (TextUtils.isEmpty(withDrawMoneyString)){
                    UIUtils.showToast("请输入提现金额");
                    return;
                }

                double withDrawMoney = Double.parseDouble(withDrawMoneyString);

                if (withDrawMoney <= 0){
                    UIUtils.showToast("取现金额不能为0");
                    return;
                }

                if (withDrawMoney > mPreWithdrawBean.available){
                    UIUtils.showToast("可用余额不足");
                    return;
                }

                mWithdrawDialog.show();
                String tel = mPreWithdrawBean.mobile;
                mDialogTelView.setText("短信已发送至："+tel.substring(0, 3)+"****"+ tel.substring(tel.length()-4));
                if (mValidateBtnView.isEnabled()){
                    sendCode();
                }
                break;
        }
    }
}
